package com.generator.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GenDBUtil {
	private static GenDBUtil genDBUtil = new GenDBUtil();
	
	private GenDBUtil(){
		
	}
	
	public static GenDBUtil getGenDBUtil(){
		return genDBUtil;
	}
	
	public Map<String, String> queryTableInfo(String tableName){
		Connection con = DBUtil.getConnection();
		Statement st = null;
		ResultSet rs = null;
		Map<String,String> map = null;
		try {
			st = con.createStatement();
			String sql = "select table_name tableName, engine, table_comment tableComment, create_time createTime from information_schema.tables "
					+ "where table_schema = (select database()) and table_name = '" + tableName + "'";
			rs =  st.executeQuery(sql);
			while(rs.next()){
				map = new HashMap<String, String>();
				map.put("tableName", rs.getString("tableName"));
				map.put("engine", rs.getString("engine"));
				map.put("tableComment", rs.getString("tableComment"));
				map.put("createTime", rs.getString("createTime"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try {
				if(st != null){
					st.close();
				}
				if(rs != null){
					rs.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return map;
	}
	
	public List<Map<String, String>> queryColumns(String tableName){
		Connection con = DBUtil.getConnection();
		Statement st = null;
		ResultSet rs = null;
		Map<String,String> map = null;
		List<Map<String, String>> list = null;
		try {
			st = con.createStatement();
			String sql = "select column_name columnName, data_type dataType, column_comment columnComment, column_key columnKey, extra from information_schema.columns"
					+ " where table_name = '" + tableName + "' and table_schema = (select database()) order by ordinal_position";
			rs =  st.executeQuery(sql);
			while(rs.next()){
				if(list == null){
					list = new ArrayList<Map<String,String>>();
				}
				map = new HashMap<String, String>();
				map.put("columnName", rs.getString("columnName"));
				map.put("dataType", rs.getString("dataType"));
				map.put("columnComment", rs.getString("columnComment"));
				map.put("columnKey", rs.getString("columnKey"));
				list.add(map);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try {
				if(st != null){
					st.close();
				}
				if(rs != null){
					rs.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return list;
	}
}
